package com.ssky.bean.validator.util;

import com.ssky.bean.validator.core.exception.VldException;

/**
 * @Author: ssky
 * @Date: 2021/07/18
 * @Description:
 */
public class ExpUtil {
    private static final String ValueExpBeginFlag = "${";
    private static final String ValueExpEndFlag = "}";


    public static final String OPERATOR_LOGIC = "!|&()";

    public static final String OPERATOR_LOGIC_RPL = "|&()";


    /**
     * 判断是否是算术表达式中的元素
     *
     * @param str
     * @return
     */
    public static boolean isElement(String str) {
        str = str.trim();
        if (OPERATOR_LOGIC.contains(str))
            return false;
        return true;
    }

    /**
     * 判断是否是算术表达式中的操作符
     *
     * @param str
     * @return
     */
    public static boolean isOperate(String str) {
        return !isElement(str);
    }

    /**
     * 判断是否是逆波兰表达式操作符
     *
     * @param str
     * @return
     */
    public static boolean isOperateRPL(String str) {
        str = str.trim();
        if (OPERATOR_LOGIC_RPL.contains(str))
            return true;
        return false;
    }


    /**
     * 转换为java操作符
     *
     * @param operate
     * @return
     */
    public static final String toJavaOperate(String operate) {
        switch (operate) {
            case "!":
            case "(":
            case ")":
                return operate;
            case "|":
                return "||";
            case "&":
                return "&&";
        }
        throw new IllegalArgumentException("\"" + operate + "\" " + "not operator(" + OPERATOR_LOGIC + ")");
    }


    public static String expParse(String param) {
        String result = null;
        param = param.trim();
        if (param.startsWith(ValueExpBeginFlag)) {
            if (!param.endsWith(ValueExpEndFlag)) {
                throw new VldException("The property value= " + param + " indeterminate !");
            }
            result = param.substring(ValueExpBeginFlag.length(), param.length() - 1).trim();
            if ("".equals(result.trim())) {
                throw new VldException("expression cannot be empyt");
            }
            if (result.contains("{") || result.contains("}")) {
                throw new VldException("The property value= " + param + " indeterminate !");
            }
        }
        return result;
    }

    public static boolean isVariable(String param) {
        param = param.trim();
        if (param.startsWith(ValueExpBeginFlag) &&
                param.endsWith(ValueExpEndFlag)) {
            String result = param.substring(ValueExpBeginFlag.length(), param.length() - 1).trim();
            if (!result.contains("{") && !result.contains("}")) {
                return true;
            }
        }
        return false;
    }
}
